package com.ruijie.acl.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jboss.seam.annotations.Transactional;
import org.springframework.util.Assert;

import com.ruijie.acl.AccessGroup;
import com.ruijie.acl.Ace;
import com.ruijie.acl.Template;
import com.ruijie.acl.TimeRange;
import com.ruijie.acl.task.model.AccessGroupInfo;
import com.ruijie.acl.task.model.AclDeviceInfo;
import com.ruijie.acl.utils.AclEntityUtil;
import com.ruijie.acl.utils.AclUtil;
import com.ruijie.foundation.dao.support.Page;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.international.web.function.MessageFunctionLibrary;
import com.ruijie.foundation.utils.StringUtils;

/**
 * <p>
 * Title: ACL模板服务接口实现类
 * 
 * </p>
 * <p>
 * Description: 为ACL模板模块提供逻辑处理，以及数据库的操作。
 * 
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time:
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */
public class TemplateServiceImpl extends AclHibernateEntityExtendDao<Template>
		implements TemplateService {
	
	private TimeRangeService timeRangeService;
	private AceService aceService;
	private AccessGroupService accessGroupService;
 

	public AccessGroupService getAccessGroupService() {
		return accessGroupService;
	}

	public void setAccessGroupService(AccessGroupService accessGroupService) {
		this.accessGroupService = accessGroupService;
	}

	/**
	 * 分布查询ACL模板
	 * 
	 * @param template
	 *            模板
	 * @param pageNo
	 *            页数
	 * @param pageSize
	 *            每面显示的记录数
	 * @return 模板列表
	 */
	public Page pagedQuery(Template template, int pageNo, int pageSize) {
		Assert.notNull(template);
		Criteria criteria = createCriteria(Template.class);
		if (!StringUtils.isNullOrEmpty(template.getName())) {
			criteria.add(Restrictions.like("name", template.getName().trim(),
					MatchMode.ANYWHERE));
		}
		if (!StringUtils.isNullOrEmpty(template.getAccessGroupType())) {
			criteria.add(Restrictions.eq("accessGroupType", template
					.getAccessGroupType().trim()));
		}
		return pagedQuery(criteria, pageNo, pageSize);
	}

	/**
	 * 判断是否存在同名的模板，排除自身
	 * 
	 * @param name
	 *            名称
	 * @param id
	 *            自身id
	 * @return true:存在 false:不存在
	 */
	public boolean isExistsTemplateName(String name, Long id) {
		Assert.notNull(name);
		Criteria criteria = createCriteria(Template.class);
		criteria.add(Restrictions.eq("name", name));

		// 如果ID号 != null ,则表示为修改，如果ID号 == null ，则为添加
		if (id != null) {
			criteria.add(Restrictions.not(Restrictions.eq("id", id)));
		}
		int total = (Integer) criteria.setProjection(Projections.rowCount())
				.uniqueResult();
		return total != 0;
	}
	
	/**
	 * 从文本导入ACL模板
	 * @param acldevice　acl设备
	 */
	@Transactional
	public List<String[]> loadTemplate(AclDeviceInfo deviceInfo){
		try {
			List<AccessGroupInfo> groupList = deviceInfo.getAccessGroupInfoList();
			if(groupList.size()==0){
				throw new BusinessException(MessageFunctionLibrary.i18n_msg("acl_template_import_dataerror").toString());
			}
			/*保存时间段信息*/
			List<TimeRange> timeRangeList = AclEntityUtil.timeRangeInfoList2TimeRangeList(deviceInfo.getTimeRangeInfoList());
			List<String[]> timeRangeResult = accessGroupService.saveTimeRangeInfo2TimeRange(timeRangeList);
			this.getSessionFactory().getCurrentSession().flush();
			
			List<AccessGroup> accessGroupList = AclEntityUtil.accessGroupInfoList2AccessGroupList(groupList);
			//导入组的提示信息
			List<String[]> importResult=new ArrayList<String[]>();
			importResult.addAll(timeRangeResult);
			//[start]判断导入组中，是否存在同名
			List<String> allGroups=new ArrayList<String>();
			for(int i=0;i<accessGroupList.size();i++){
				String name=accessGroupList.get(i).getName();
				String validateResult = AclUtil.validateGroupName(name,accessGroupList.get(i).getAclType());
				if(validateResult.length()>0){
					if("acl_group_maxlength".equals(validateResult)){
						throw new BusinessException(validateResult);
					}else{
						throw new BusinessException(validateResult+"_template",name);
					}
					
				}
				if(allGroups.contains(name)||name==null){
					throw new BusinessException("acl_template_import_nameExites");
				}else{
					allGroups.add(name);
				}
			}
			//[end]
			for(AccessGroup accessGroup:accessGroupList){
				int orign=accessGroup.getAces().size();
				List<String[]> result=AclUtil.filterAndValidateAccessGroup(accessGroup);
				int successCount=accessGroup.getAces().size();
				int failtCount=orign-successCount;
				//导入ACL模板：{0}，成功导入规则{1}条，失败{2}条。
				importResult.add(new String[]{
						"acl_template_ace_import_info",
						accessGroup.getName(),
						new Integer(successCount).toString(),
						new Integer(failtCount).toString()
						});
				if(result!=null&&result.size()>0){
					importResult.addAll(result);
				}
			}
			/*保存ACL模板信息*/
			this.saveLoadTemplate(accessGroupList);
			return importResult.size()>0?importResult:null;
		}catch (BusinessException bex) {
			throw bex;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
	}
	
	/**
	 * 从设备导入ACL模板
	 * @param acldevice　acl组
	 */
	public void loadTemplateFromDevice(List<AccessGroup> accessGroupList){
		/*保存时间段信息
		for (AccessGroup entity : accessGroupList){
			List<TimeRange> timeRangeList = timeRangeService.findByAccessGroup(entity);
			accessGroupService.saveTimeRangeInfo2TimeRange(timeRangeList);
		}*/
		/*保存ACL模板信息*/
		this.saveLoadTemplate(accessGroupList);
	}
	
	/**
	 * 保存ACL模板
	 * @param list 设备的ACL组列表
	 */
	public void saveLoadTemplate(List<AccessGroup> accessGroupList){
		//遍历AccessGroup>处理
		//取得template信息
		Template template = null;
			for (AccessGroup entity : accessGroupList){
				boolean existTemplate = false;
				List<Ace> aceList = entity.getAces();
				if (aceList == null){
					aceList = new ArrayList<Ace>();
				}
				if (aceList.size() > 0 && aceList.get(0) == null){
					aceList.remove(0);
				}
				//进行DB存在验证template
				
				existTemplate = isExistsTemplateName(entity.getName(), null);
				
				if (!existTemplate){
					//不存在时
					//保存AccessGroup
					template = AclEntityUtil.accessGroup2Template(entity);
					save(template);
					//保存所有ACE
					for (Ace ace : aceList){
						//存在则设置TimeRange对象
						//不存在时设置TimeRange为null 
						Ace tempAce = ace.clone(template, timeRangeService.getByNameWithoutAclDevice(ace.getTimeRangeName()));
						AclUtil.filterAce(tempAce, entity.getAclType());
						tempAce.setAceNum(0);
						aceService.save(tempAce);
					}
				}else{
					throw new BusinessException(MessageFunctionLibrary.i18n_msg("acl_template_import_nameExites").toString());
				}
			}
	}

	public TimeRangeService getTimeRangeService() {
		return timeRangeService;
	}

	public void setTimeRangeService(TimeRangeService timeRangeService) {
		this.timeRangeService = timeRangeService;
	}

	public AceService getAceService() {
		return aceService;
	}

	public void setAceService(AceService aceService) {
		this.aceService = aceService;
	}
}
